<template>
  <view class="flex-col page">
    <view>
      <u-sticky bgColor="#fff">
        <u-tabs
          :current="tabsIndex"
          @click="click"
          style="background-color: #ffffff"
          :list="list4"
          lineWidth="20"
          lineColor="#38987c"
          :activeStyle="{
            color: '#38987c',
            fontWeight: 'bold',
            transform: 'scale(1)',
          }"
          :inactiveStyle="{
            color: '#333',
            transform: 'scale(1)',
          }"
        >
        </u-tabs>
      </u-sticky>

      <view class="flex-col group">
        <view class="flex-col">
          <view class="flex-col group_2">
            <view class="section_3"> </view>
            <view class="flex-col list">
              <u-skeleton
                rows="10"
                :loading="loading"
                :title="false"
                rowsHeight="170"
                style="margin-top: 30rpx"
              ></u-skeleton>
              <view class="no" v-if="isEmpty">
                <zNo></zNo>
              </view>
              <view
                class="list-item flex-col"
                :key="i"
                v-for="(item, i) in dataList"
                @click.stop="onClick($event, item)"
              >
                <view class="top-section justify-between">
                  <text class="t1">{{ item.name }}</text>
                  <text class="text_7" v-if="item.order_status == 0"
                    >待支付</text
                  >
                  <text class="text_71" v-if="item.order_status == 1"
                    >待接单</text
                  >
                  <text class="text_72" v-if="item.order_status == 2"
                    >待服务</text
                  >
                  <text class="text_73" v-if="item.order_status == 3"
                    >服务中</text
                  >
                  <text class="text_74" v-if="item.order_status == 4"
                    >服务完成</text
                  >
                  <text class="text_74" v-if="item.order_status == 5"
                    >已评价</text
                  >
                  <text class="text_75" v-if="item.order_status == 6"
                    >已取消</text
                  >
                  <text class="text_75" v-if="item.order_status == 7"
                    >退款</text
                  >
                  <text class="text_73" v-if="item.order_status == 8"
                    >出发</text
                  >
                  <text class="text_73" v-if="item.order_status == 9"
                    >到达</text
                  >
                </view>
                <view class="center-group flex-row">
                  <view class="right-group flex-col">
                    <text class="text_13"
                      >服务时间：{{ item.appointment_time }}</text
                    >
                    <text class="text_9"
                      >服务技师：{{
                        item.realname ? item.realname : item.nickname
                      }}</text
                    >
                    <view class="bottom-group">
                      <view>
                        <text class="text_15">合计</text>
                        <text class="text_17 price-font"
                          >￥{{ item.pay_money }}</text
                        >
                      </view>
                      <view class="flex" style="padding-top: 60rpx">
                        <view
                          class="left-text-wrapper flex-col items-center"
                          id="hide"
                          v-if="item.order_status <= 2"
                        >
                          <text id="hide">取消订单</text>
                        </view>
                        <view
                          style="margin-right: 10rpx"
                          class="right-text-wrapper flex-col items-center"
                          id="pay"
                          v-if="item.order_status == 0"
                        >
                          <text id="pay">立即支付</text>
                        </view>
                        <view
                          class="left-text-wrapper4 flex-col items-center"
                          id="cancel"
                          v-if="[0, 4, 5, 6, 7].indexOf(item.order_status) >= 0"
                        >
                          <text id="cancel">删除订单</text>
                        </view>
                        <view
                          class="left-text-wrapper5 flex-col items-center"
                          id="comment"
                          v-if="item.order_status == 4"
                        >
                          <text id="comment">评价</text>
                        </view>
                        <view
                          class="left-text-wrapper5 flex-col items-center"
                          id="toushu"
                          v-if="
                            item.order_status == 4 || item.order_status == 5
                          "
                        >
                          <text id="toushu">投诉</text>
                        </view>

                        <view
                          class="right-text-wrapper3 flex-col items-center complete"
                          id="complete"
                          v-if="item.order_status == 3"
                        >
                          <text id="complete">提前完成</text>
                        </view>

                        <view
                          class="right-text-wrapper3 flex-col items-center"
                          id="addserv"
                          v-if="item.order_status == 3"
                        >
                          <text id="addserv">加钟</text>
                        </view>

                        <view
                          class="right-text-wrapper3 flex-col items-center"
                          id="upgrade"
                          v-if="
                            item.order_status == 2 || item.order_status == 3
                          "
                        >
                          <text id="upgrade">升级服务</text>
                        </view>
                      </view>
                    </view>
                  </view>
                </view>
              </view>
              <view class="list-item" style="height: 100rpx; opacity: 0"></view>
            </view>
          </view>
        </view>
      </view>
      <!-- <zPay ref="pay" :money="pay_money" :balance="balance" @pay="pay" @closePay='closePay'></zPay> -->
      <view class="kf" @click="calltel"></view>
    </view>
  </view>
</template>

<script>
// import tmSkeleton from "@/tm-vuetify/components/tm-skeleton/tm-skeleton.vue";
import zNo from "@/components/z-no/index.vue";
export default {
  components: {
    // tmSkeleton,
    zNo,
    // zPay
  },
  data() {
    //0待付款；1待确认；2待服务；3进行中;4完成；5评价；6取消订单
    return {
      list4: [
        {
          name: "全部",
          status: "",
        },
        {
          name: "待接单",
          status: 1,
        },
        {
          name: "待服务",
          status: 2,
        },
        {
          name: "进行中",
          status: 3,
        },
        {
          name: "已完成",
          status: 4,
        },
        {
          name: "已取消",
          status: 6,
        },
      ],
      mobiles: "",
      loading: true,
      tabsIndex: 0,
      dataList: [],
      page: 1,
      total: null,
      isEmpty: false,
      pay_money: 0,
      balance: 0,
      isLogin: false,
      popupshow: false,
      lockData: [],
      selectIndex: 0,
      clock_id: 0,
      payType: "",
      payList: [],
      user: "",
      isPay: false,
      selected_order_sn: "",
      clockOrder: [],
    };
  },
  onLoad() {
    var that = this;
    this.payList = [
      {
        name: "账户余额",
      },
      {
        name: "微信支付",
      },
    ];

    let active = uni.getStorageSync("tabsIndex");
    if (active) {
      this.tabsIndex = Number(active);
      uni.removeStorageSync("tabsIndex");
    }
    this.getUserinfo();

    let location = uni.getStorageSync("location");
    if (location) {
      location = JSON.parse(location);
    } else {
      location = { lat: 0, lng: 0 };
    }
    this.$http
      .post(`api/user/customerService?lat=${location.lat}&lng=${location.lng}`)
      .then((res) => {
        let { mobile } = res;
        this.mobiles = mobile;
      });
  },
  onShow() {
    this.isLogin = uni.getStorageSync("userInfo");
    if (this.isLogin) {
      uni.$u.sleep(500).then(() => {
        this.page = 1;
        this.dataList = [];
        this.total = null;
        this.init(1);
      });
    }
  },
  onPullDownRefresh() {
    let _self = this;
    console.log("refresh");
    setTimeout(() => {
      uni.stopPullDownRefresh(); //停止当前页面下拉刷新
      this.page = 1;
      this.dataList = [];
      this.total = null;
      this.init();
    }, 500);
  },
  onReachBottom() {
    if (this.dataList.length === this.total) {
      return;
    }
    this.page++;
    this.init();
  },
  methods: {
    // pay,
    calltel() {
      if (this.mobiles) {
        uni.showModal({
          content: "是否拨打客服电话",
          success: (res) => {
            if (res.confirm) {
              uni.makePhoneCall({
                phoneNumber: this.mobiles + "",
              });
            }
          },
        });
        return;
      }
      uni.showToast({
        icon: "none",
        title: "暂无客服联系号码",
      });
    },
    fill(a) {
      return 10 > a ? "0" + (0 | a) : a;
    },
    wxPay(order_sn) {
      var that = this;
      let date = new Date();
      let create_time =
        date.getFullYear() +
        "-" +
        this.fill(Number(date.getMonth()) + 1) +
        "-" +
        this.fill(date.getDate()) +
        this.fill(date.getHours()) +
        ":" +
        this.fill(date.getMinutes()) +
        ":" +
        this.fill(date.getDate());
      uni.setStorageSync("order_info", {
        create_time,
        order_sn: order_sn,
        pay_type: "微信支付",
        pay_money: this.pay_money,
      });
    },
    async createClock() {
      this.isPay = true;
      if (!this.payType) {
        uni.showToast({
          icon: "none",
          title: "请选择支付方式",
        });
        this.isPay = false;
        return;
      }
      if (
        this.payType === "账户余额" &&
        this.lockData[this.selectIndex].price > Number(this.user.balance)
      ) {
        uni.showToast({
          icon: "none",
          title: "账户余额不足",
        });
        this.isPay = false;
        return;
      }
      this.pay_money = this.lockData[this.selectIndex].price;

      let order_info = uni.getStorageSync("order_info");
      if (!order_info) {
        order_info = {};
      }
      order_info.pay_money = this.pay_money;
      uni.setStorageSync("order_info", order_info);
      this.pay_form = "clock";
      await this.$http
        .post("api/order/createClock", {
          order_sn: this.selected_order_sn,
          clock_id: this.lockData[this.selectIndex].id,
        })
        .then((res) => {
          this.clockOrder = res;
        })
        .catch((err) => {
          this.isPay = false;
          die;
        });
      let pay_way =
        this.payType === "账户余额" ? 1 : this.payType === "微信支付" ? 2 : 3;
      if (pay_way !== 1) {
        this.wxPay(this.clockOrder);
      } else {
        await this.$http
          .post("api/pay/pay", {
            order_sn: this.clockOrder,
            pay_way,
            form: this.pay_form,
          })
          .then((res) => {
            uni.navigateTo({
              url: "/bundle/pages/pay_success/pay_success",
            });
            this.isPay = false;
          })
          .catch((err) => {
            this.isPay = false;
            this.$http.post("api/order/cancelClock", {
              order_sn: this.clockOrder,
            });
          });
      }
    },
    getUserinfo() {
      this.$http.post("api/user/userInfo").then((res) => {
        this.user = res;
      });
    },
    selectTime(index, item) {
      this.selectIndex = index;
      this.clock_id = item.id;
    },
    toLogin() {
      uni.navigateTo({
        url: "/pages/user/login22",
      });
    },
    completeOrder(order_sn) {
      var that = this;
      uni.showModal({
        title: "提示",
        content: "是否确认提交完成?",
        confirmText: "确认",
        complete(e) {
          if (e.confirm) {
            uni.showLoading({
              mask: true,
            });
            let options = {
              url: `${that.$base.baseUrl}api/order/completeOrder`,
              data: { order_sn },
              header: {},
              success(res) {
                uni.showToast({
                  title: res.data.msg,
                  icon: "none",
                });
              },
              complete() {
                uni.hideLoading();
                that.page = 1;
                that.dataList = [];
                that.init();
              },
            };
            let storeUserInfo = uni.getStorageSync("userInfo");
            if (storeUserInfo.token) {
              options.header.token = storeUserInfo.token;
            }
            uni.request(options);
          }
        },
      });
    },
    init() {
      this.$http
        .post("api/order/orderList", {
          order_status: this.list4[this.tabsIndex].status,
          page: this.page,
        })
        .then((res) => {
          let { list, total, count } = res;
          this.dataList.push(...list);
          this.total = count;
          this.loading = false;
          if (this.total === 0) {
            this.isEmpty = true;
          } else {
            this.isEmpty = false;
          }
        });
      this.$http.post("api/user/userInfo").then((res) => {
        this.balance = res.balance;
      });
    },
    click(e) {
      let { index } = e;
      this.tabsIndex = index;
      this.page = 1;
      this.dataList = [];
      this.init();
    },
    onClick(e, item) {
      let id = e.target.id;
      if (id === "hide") {
        uni.navigateTo({
          url: `/addPage/pages/hideorder?order_sn=${item.order_sn}`,
        });
        return;
      }
      if (id == "upgrade") {
        uni.navigateTo({
          url: `/pages/order/add?ordid=${item.order_sn}&tab=0`,
        });
        return;
      }
      if (id == "addserv") {
        uni.navigateTo({
          url: `/pages/order/add?ordid=${item.order_sn}&tab=1`,
        });
        return;
      }
      if (id === "toushu") {
        uni.navigateTo({
          url: "/bundle/pages/complaint/complaint?order_id=" + item.id,
        });
        return;
      }
      if (id === "comment") {
        uni.navigateTo({
          url:
            "/bundle/pages/orderComment/orderComment?order_sn=" + item.order_sn,
        });
        return;
      }
      if (id === "complete") {
        this.completeOrder(item.order_sn);
        return;
      }
      if (id === "cancel") {
        uni.showModal({
          title: "提示",
          content: "是否确认删除订单？",
          success: (res) => {
            console.log(res);
            if (res.confirm) {
              this.$http
                .post("api/order/cancelDelete", {
                  order_sn: item.order_sn,
                })
                .then((res) => {
                  uni.showToast({
                    icon: "none",
                    title: "删除成功",
                  });
                  this.page = 1;
                  this.dataList = [];
                  this.init();
                })
                .catch((err) => {
                  uni.showToast({
                    icon: "none",
                    title: "删除失败",
                  });
                });
            }
          },
        });

        return;
      }
      uni.navigateTo({
        url:
          "/bundle/pages/order_details/order_details?order_sn=" + item.order_sn,
      });
    },
    hide(item) {
      uni.showModal({
        content: "是否确认取消订单？如果技师已经接单，会扣除一定费用",
        success: (res) => {
          console.log(res);
          if (res.confirm) {
            this.$http
              .post("api/order/cancelOrder", {
                order_sn: item.order_sn,
              })
              .then((res) => {
                this.$http
                  .post("api/order/confirmCancel", {
                    order_sn: item.order_sn,
                  })
                  .then((res) => {
                    uni.showToast({
                      icon: "none",
                      title: "取消成功",
                    });
                  });

                this.tabsIndex = 5;
                this.page = 1;
                this.dataList = [];
                this.init();
              });
          }
        },
      });
    },
  },
};
</script>

<style scoped lang="scss">
@import "./index.scss";
</style>
